using System;
using System.Collections;
using UnityEngine;

public class CouponLayer : UILayer
{
	public UIInput input;

	public UILabel coupon;

	public UILabel statusLabel;

	public string couponUrl = string.Empty;

	private bool inRequest;

	private void OnEnable()
	{
		Ads.instance.hideBanner(true);
	}

	private void OnDisable()
	{
		Ads.instance.hideBanner(false);
	}

	public new void OnEnter()
	{
		statusLabel.text = string.Empty;
	}

	public void RedeemCoupon()
	{
		if (inRequest)
		{
			statusLabel.text = "Currently Checking coupon...";
			return;
		}
		StartCoroutine(DoRedeemCoupon(coupon.text));
		statusLabel.text = "Checking coupon...";
	}

	private IEnumerator DoRedeemCoupon(string couponText)
	{
		bool giraffeDollars = false;
		bool diamonds = false;
		CurrencyType currency = CurrencyType.coins;
		if (couponText.StartsWith("gd") && couponText.Length >= 7)
		{
			couponText = couponText.Substring(2);
			currency = CurrencyType.ggdollars;
		}
		else if (couponText.StartsWith("di") && couponText.Length >= 7)
		{
			couponText = couponText.Substring(2);
			currency = CurrencyType.diamonds;
		}
		if (!GGSupportMenu.instance.isNetworkConnected())
		{
			statusLabel.text = "No internet connection, please check your internet connection and try again";
		}
		inRequest = true;
		WWW request = new WWW(couponUrl + couponText + "&ts=" + DateTime.Now.Ticks);
		yield return request;
		if (!string.IsNullOrEmpty(request.error) || string.IsNullOrEmpty(request.text))
		{
			statusLabel.text = "Error with the request, please check your internet connection or try again later";
		}
		else if (request.text == "redeemed")
		{
			statusLabel.text = "Coupon already redeemed";
		}
		else if (request.text == "no")
		{
			statusLabel.text = "Wrong coupon code, please check and try again";
		}
		else
		{
			int result = 0;
			if (int.TryParse(request.text, out result))
			{
				GGPlayerSettings.instance.walletManager.ReceiveCurrency(currency, Mathf.Max(result, 0));
			}
			string @string = ScriptableObjectSingleton<SettingsUI>.instance.GetString(currency.ToString());
			statusLabel.text = "Coupon redeemed, added " + result + " " + @string;
		}
		inRequest = false;
	}

	public void OnDone()
	{
		if (inRequest)
		{
			UIDialog.instance.ShowOk("In Request", "Please wait till the coupon is checked", "OK", null);
		}
		else
		{
			NavigationManager.instance.Pop();
		}
	}
}
